package com.example.personalizededucationsystem.service;

import com.example.personalizededucationsystem.dto.request.CreateClassRequest;
import com.example.personalizededucationsystem.dto.request.StudentClassInfoDTO;
import com.example.personalizededucationsystem.model.Class;
import com.example.personalizededucationsystem.model.ClassMember;
import com.example.personalizededucationsystem.model.User;
import com.example.personalizededucationsystem.repository.ClassMemberRepository;
import com.example.personalizededucationsystem.repository.ClassRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
public class ClassService {

    private final ClassRepository classRepository;
    private final ClassMemberRepository classMemberRepository;

    @Autowired
    public ClassService(ClassRepository classRepository, ClassMemberRepository classMemberRepository) {
        this.classRepository = classRepository;
        this.classMemberRepository = classMemberRepository;
    }

    public List<Class> getClassesByTeacher(Long teacherId) {
        return classRepository.findByTeacherUserId(teacherId);
    }

    /**
     * 创建一个新班级
     *
     * @param request 包含班级信息的请求
     * @param teacher 创建班级的教师用户
     * @return 创建好的班级实体
     */
    public Class createClass(CreateClassRequest request, User teacher) {
        Class newClass = new Class();
        newClass.setClassName(request.getClassName());
        newClass.setSubject(request.getSubject());
        newClass.setDescription(request.getDescription());
        newClass.setTeacher(teacher);

        String invitationCode = generateUniqueInvitationCode();
        newClass.setInvitationCode(invitationCode);

        return classRepository.save(newClass);
    }


    public List<StudentClassInfoDTO> getClasses(User user) {
        return classMemberRepository.findClassesByStudentId(user.getUserId())
                .stream()
                .map(StudentClassInfoDTO::new)
                .toList();
    }

    /**
     * 【新增】学生使用邀请码加入班级
     */
    @Transactional
    public void joinClass(String invitationCode, User student) {
        Class classToJoin = classRepository.findByInvitationCode(invitationCode).orElseThrow(() -> new EntityNotFoundException("无效的邀请码"));

        if (classMemberRepository.existsByStudentAndMyClass(student, classToJoin)) {
            throw new IllegalStateException("您已经在这个班级里了");
        }
        ClassMember newMembership = new ClassMember();
        newMembership.setStudent(student);
        newMembership.setMyClass(classToJoin);
        classMemberRepository.save(newMembership);
    }

    /**
     * 【新增】获取指定班级内的所有学生名单
     */
    public List<ClassMember> getStudentsInClass(Long classId, User teacher) {

        Class myClass = classRepository.findById(classId).orElseThrow(() -> new EntityNotFoundException("班级未找到，ID: " + classId));
        return classMemberRepository.findByMyClass(myClass);
    }

    private String generateUniqueInvitationCode() {
        String code;
        do {
            code = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        } while (classRepository.findByInvitationCode(code).isPresent());
        return code;
    }
}